import React, { useContext, useEffect, useState } from 'react';
import WsPlayer from '../../../../../../../../WsPlayer';
import FetchHelper from '../../../../../../../../utils/helper/fetch-helper';
import './VideoMonitor.css';
import jcyjContext from '../jcyjContext';
import { Tree } from 'antd';


const wsPlayerInstance = (a) => {

    return (
        <WsPlayer
            playParams={{
                rtspURL: a.rURL,
                wsURL: a.wURL,
                channelId: a.cId
            }}
            width={800}
            height={590} // 调整为与视频监视器内容区域高度相同
        />
    );

}

const deviceTreeApi = async (deviceId = null) => {
    try {
        const resp = await FetchHelper.postJson(`/admin-api/ybyj/sp/device/Tree`, {
            type: "001;;1",
            id: deviceId,
            checkStat: 1
        });
        //console.log('接口数据', resp, "接口id:", deviceId, "接口传递的数据", resp?.data?.data?.value);
        return resp?.data?.data?.value;
    } catch (error) {
        console.error('获取设备数据失败:', error);
    }
    return null; // 如果出错，返回 null
}


export default function VideoMonitor(props) {

    const { setIsClosed, isClosed } = useContext(jcyjContext)
    const [deviceTree, setDeviceTree] = useState([]);
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [hoveredDeviceId, setHoveredDeviceId] = useState(null);
    const [loadingDeviceId, setLoadingDeviceId] = useState(null);
    const [channelId, setChannelId] = useState();
    const [rtspURL, setRtspURL] = useState();
    const [wsURL, setWsURL] = useState();


    // 加载初始设备树
    const loadInitialTree = async () => {
        //console.log('加载初始设备');
        const initialData = await deviceTreeApi(); // 可以根据需要初始加载
        setDeviceTree(initialData || []);
    };

    useEffect(() => {
        loadInitialTree();
        setRtspURL(null)
        setChannelId(null)
    }, [isClosed]);
    useEffect(() => {
        //console.log('设备树更新', deviceTree);
        //loadInitialTree();
        setLoadingDeviceId(null); // 清除加载状态
    }, [deviceTree]);

    // 加载子设备
    const loadChildren = async (deviceId) => {
        if (deviceId.includes('$')) {
            console.log(`Device with ID "${deviceId}" has no children. Returning this channel ID.`);
            setChannelId(deviceId)
            console.log('获取id');
            return deviceId; // 返回通道 ID
        }

        const children = await deviceTreeApi(deviceId);
        return children || []; // 返回子设备或空数组
    };



    const updateDeviceTree = (devices, deviceId, children) => {
        //console.log(`子设备树挂载`, devices, 'id', deviceId, '子设备', children);
        return devices.map(device => {
            if (device.id === deviceId) {
                //console.log(`找到设备`);
                return {
                    ...device,
                    children: children
                };
            }
            if (device.children) {
                //console.log(`查找子节点设备`);
                return {
                    ...device,
                    children: updateDeviceTree(device.children, deviceId, children),
                };
            }
            //console.log(`没有找到设备`, devices, 'id', deviceId, '子设备', children);
            return device;
        });
    };

    const handleDeviceClick = async (deviceId) => {
        //console.log(`点击了我`, deviceId);
        setLoadingDeviceId(deviceId); // 设置加载状态

        const children = await loadChildren(deviceId);
        //console.log(`返回的子设备`, children);
        if (Array.isArray(children)) {
            const updatedTree = updateDeviceTree(deviceTree, deviceId, children);
            setDeviceTree(updatedTree);

            setExpandedKeys(prev => {
                if (prev.includes(deviceId)) {
                    return prev.filter(id => id !== deviceId); // 收起
                } else {
                    return [...prev, deviceId]; // 展开
                }
            });
        } else {
            console.log(`Selected channel ID: ${children}`);
        }
    };



    //递归渲染设备树
    const renderDeviceTree = (devices) => {
        //console.log(`设备树 `, devices);
        return devices.map(device =>
            <div key={device.id} className='redBGC' onClick={(event) => { event.stopPropagation(); handleDeviceClick(device.id) }}>
                <span>{device.name}</span>

                {expandedKeys.includes(device.id) && device.children && (
                    <div>
                        {renderDeviceTree(device.children)} {/* 递归渲染子设备 */}
                    </div>
                )}
            </div>);
    };



    //实时预览
    useEffect(() => {

        const real_timePreview = async (channelId = null) => {
            //setLoadingDeviceId([1,2,3])
            //console.log("接口id:", channelId,);
            try {
                const resp = await FetchHelper.postJson(`/admin-api/evo-apigw/admin/API/MTS/Video/StartVideo`, {
                    channelId: `${channelId}`
                });
                //console.log('接口数据', resp, "接口id:", channelId, "接口传递的数据", resp?.data?.data?.value);
                return resp;
            } catch (error) {
                console.error('获取设备数据失败:', error);
            }
            return null; // 如果出错，返回 null
        }
        if (channelId) {
            real_timePreview(channelId).then(resp=>{
                setRtspURL(resp?.data?.outer_url)
                setLoadingDeviceId(null);
            })
        }

    }, [channelId]);



    const handleCloseClick = () => {
        setIsClosed(true);
    };



    return (

        <div className='video-monitor'>

            {!isClosed && <><div className="video-monitor-header" >
                视频监控{loadingDeviceId ? '      加载中...' : null}
                <button className="video-monitor-close-button" onClick={handleCloseClick}>
                    X
                </button>
            </div>
                <div style={{ display: 'flex' }}>
                    <div style={{ overflowY: 'auto', height: '500px' }}>
                        {deviceTree.length > 0 ? renderDeviceTree(deviceTree) : <p>加载中...</p>}
                    </div>
                    <div style={{ marginLeft: 5, }}>
                        {channelId && rtspURL && 
                        <WsPlayer
                            playParams={{
                                rtspURL: `${rtspURL}`,
                                wsURL: `ws://117.172.163.46:9100`,
                                channelId: `${channelId}`
                            }}
                            // playParams={{
                            //     rtspURL: `rtsp://117.172.163.46:9100/dss/monitor/param/cameraid=1000111%240%26substream=1?token=5190930`,
                            //     wsURL: `ws://117.172.163.46:9100`,
                            //     channelId: `1000111$1$0$0`
                            // }}
                            width={800}
                            height={590} // 调整为与视频监视器内容区域高度相同
                        />
                        } 
                    </div>
                </div>
            </>}



        </div>
    );
}